<template>
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    title="选择物料"
    style="min-width: 900px"
    draggable
    @close="closeDialog"
    class="maxhDialog"
  >
    <div class="search-container">
      <el-form :model="searchParam" :inline="true">
        <el-form-item label="物料号">
          <el-input
            v-model="searchParam.materialCode"
            placeholder="请输入物料号"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="物料名称">
          <el-input
            v-model="searchParam.materialName"
            placeholder="请输入物料名称"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-card shadow="never" class="table-container">
      <div class="formTable">
        <el-table
          :data="tableData"
          style="width: 100%"
          :key="Math.random"
          max-height="450"
          highlight-current-row
          @current-change="handleCurrentChange1"
          v-loading="loading"
          border
        >
          <el-table-column
            label="物料码"
            prop="materialCode"
            min-width="100"
            show-overflow-tooltip
            align="left"
          />
          <el-table-column
            label="物料名称"
            prop="materialName"
            min-width="100"
            show-overflow-tooltip
            align="left"
          >
            <template #default="scope">
              <span style="text-align: left">
                {{ scope.row.materialName }}</span
              >
            </template>
          </el-table-column>
          <!-- <el-table-column
            label="物料类型"
            prop="materialType"
            min-width="100"
            show-overflow-tooltip
            align="left"
          >
            <template #default="scope">
              {{ useDictionary("MaterialType", scope.row.materialType) }}
            </template>
          </el-table-column> -->
          <el-table-column
            label="物料组"
            prop="materialGroupName"
            min-width="100"
            show-overflow-tooltip
            align="left"
          />
          <!-- <el-table-column
            label="工序"
            prop="materialGroupName"
            min-width="100"
            show-overflow-tooltip
            align="left"
          /> -->
          <!-- <el-table-column
            label="供应商"
            prop="makerName"
            min-width="100"
            show-overflow-tooltip
            align="left"
          /> -->
          <!-- <el-table-column
            label="是否重要"
            prop="importantLevel"
            min-width="60"
            show-overflow-tooltip
            align="center"
          >
            <template #default="scope">
              <el-tag type="success" v-if="scope.row.importantLevel == 1"
                >是</el-tag
              >
              <el-tag type="info" v-else-if="scope.row.importantLevel"
                >否</el-tag
              >
            </template>
          </el-table-column> -->
        </el-table>
        <el-pagination
          :background="true"
          :current-page="pageable.pageNum"
          :page-size="pageable.pageSize"
          :page-sizes="[10, 25, 50, 100]"
          :total="pageable.total"
          layout="total, sizes, prev, pager, next, jumper"
          class="mt-[20px]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确 定 </el-button>
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { useTable, useDictionary } from "@/utils/useTable";
import { ElMessage, ElForm } from "element-plus";
import { ref, reactive, watch, onBeforeUnmount } from "vue";
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();
defineOptions({
  name: "NPMWORKORDEREQUIPPLAN",
  inheritAttrs: false,
});

const emit = defineEmits(["change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  brekList: {
    type: Object,
    default: () => {
      return {};
    },
  },
});
const multipleTable = ref();
const getBreakList = () => {
  //定义了一个空数组
  let checkedrow: any = [];
  //循环列表所有的数据
  tableData.value.forEach((item) => {
    //循环后台返回需要打钩的数据
    props.brekList.forEach((v) => {
      //这就是个条件  根据自己的条件去写
      if (item.id == v.mesWorkOrderPlanId) {
        console.log(item);

        //给空数组里面添加我需要回显打钩的数据
        checkedrow.push(item); // 相等添加到空数组中
      }
    });
  });
  //最主要的就是这个方法这个方法在dom渲染完会去回调
  nextTick(() => {
    //遍历回显数组
    checkedrow.forEach((row) => {
      console.log(111111);

      //singleTableRef这个是在table上面加的ref的值  通过它的属性方法去看那几个属性打钩
      multipleTable.value.toggleRowSelection(row, true); // 回显
    });
  });

  console.log(999);

  // tableData.value.forEach((item: any) => {
  //   if (item.id === props.brekList[0].mesWorkOrderPlanId) {
  //     multipleTable.value.toggleRowSelection(item, true);
  //   }
  // });
};

//获取表格数据 api 方法
const requestApi = "/wms/mdmmaterial/queryByPage";
//获取数据初始化参数
const initParam = {};
// 初始化搜索参数数据
// 初始化搜索参数数据
const searchParamInit = {
  materialName: "",
  materialCode: "",
};
// 是否需要分页
const pagination = true;
// 无需二次数据处理&不传赞数也行
const dataCallBack = (data: any, parentIndex = "") => {
  // data.forEach((item: any, index: number) => {
  //   const currentIndex =
  //     parentIndex === ""
  //       ? (index + 1).toString()
  //       : `${parentIndex}.${index + 1}`;
  //   item.parentIndex = currentIndex;
  //   if (item.children && item.children.length > 0) {
  //     dataCallBack(item.children, currentIndex);
  //   }
  // });
  return data;
};

// 数据请求错误后处理
function requestError() {}
//删除
const deleteParam = {
  api: "",
  data: {},
};

const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack,
  requestError,
  deleteParam
);

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    getTableList();
    //getMdmMaterialList();
    if (props.brekList.length > 0) {
      console.log(4444);

      // getBreakList();
    }
  }
);

// 选择高亮
const currentRow = ref();
const handleCurrentChange1 = (val: any) => {
  currentRow.value = val;
};

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  handelRest();
}

const handelRest = () => {
  searchParam.value.materialName = "";
  searchParam.value.materialCode = "";
  // search();
};

/** email消息发送记录保存提交 */
function handleSubmit() {
  if (currentRow.value) {
    emit("change-visible", false, currentRow.value);
  } else {
    return ElMessage.warning("请选择物料");
  }
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});

onMounted(() => {
  getTableList();
  // getMdmMaterialList();
  getMakerList();
});

// 获取制造商列表
const makerList: any = ref([]);
const getMakerList = async () => {
  request({
    url: `/wms/mdmpartner/getOptionList`,
    method: "post",
    data: {},
  })
    .then((res) => {
      makerList.value = res.data;
    })
    .catch((res) => {
      console.log(res);
    });
};
// 获取mdm主数据物料
const tableDatas = ref([]);
const mdmMaterialList = ref([]);
const getMdmMaterialList = async () => {
  if (!searchData.materialName && !searchData.materialCode) {
    return ElMessage.warning("搜索项不能为空");
  }
  const res = await request({
    method: "post",
    url: `npm/mdmmaterial/getList  `,
    data: {
      materialName: searchData.materialName,
      materialCode: searchData.materialCode,
      makerId: searchData.makerId,
      importantLevel: searchData.importantLevel,
    },
  });
  mdmMaterialList.value = res.data;
};

const searchData = reactive({
  makerId: "",
  importantLevel: "",
  materialName: "",
  materialCode: "",
});
// 搜索
const searchs = () => {
  getMdmMaterialList();
};
// 重置
const resets = () => {
  searchData.makerId = "";
  searchData.importantLevel = "";
  searchData.materialName = "";
  searchData.materialCode = "";
  getMdmMaterialList();
};
</script>

<style scoped lang="scss">
.progress {
  color: red;
}
.success {
  color: rgb(100, 207, 86);
}
:deep(.maxhDialog .el-dialog__body) {
  max-height: 600px;
  overflow-y: auto;
  padding: 20px;
}
</style>
